
package biblio.service.reader;


import biblio.util.SourceName;
import biblio.util.interfaces.RegexContainer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * Validates setting name of e-mail.
 * @author mephisto
 */
@ManagedBean
@RequestScoped
public class EmailValidator implements Validator
{
    public void validate(FacesContext context, UIComponent component, Object value)
            throws ValidatorException
    {
        if (value != null)
        {
            String val = value.toString().trim();
            log.debug("E-mail for validation: " + val);
            RegexContainer regColl = (RegexContainer)appContext.getBean("regexMap");
            Pattern pattern = regColl.getPattern("email");
            Matcher matcher = pattern.matcher(val);

            ///PatternSyntaxException
            if (!matcher.find())
            {
                log.error(val + "is not a valid e-mail!");
                FacesMessage message = new FacesMessage(
                           "E-mail validation", val + " is not a valid e-mail!");
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message);
            }
        }
        else
        {
            FacesMessage message = new FacesMessage(
                           "E-mail validation", "Empty value is not permitted!");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message);
        }
    }


    static
    {
        appContext = new ClassPathXmlApplicationContext( new String[] {
                SourceName.AUX_APPLICATION_CONTEXT
        });
    }


    private static ApplicationContext appContext;
    private static Logger log = Logger.getLogger(EmailValidator.class);
}
